package cn.wolfcode.p2p.website.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.base.util.JSONResult;
import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.business.query.CreditTransferQueryObject;
import cn.wolfcode.p2p.business.service.ICreditTransferService;

/**
 * 债权转让控制器
 * 
 * @author wolfcode
 *
 */
@Controller
public class CreditTransferController {

	@Autowired
	private ICreditTransferService creditTransferService;

	/**
	 * 列出我可以转让的债权信息
	 * 
	 * @param qo
	 * @param model
	 * @return
	 */
	@RequestMapping("listCanTransferCredit")
	public String listCanTransferCredit(@ModelAttribute("qo") CreditTransferQueryObject qo, Model model) {
		model.addAttribute("pageResult", this.creditTransferService.listCanTransferCredit(qo));
		return "credittrans/credittransfer_cantrans_list";
	}

	/**
	 * 生成债权转让标
	 */
	@RequestMapping("creditTransfer")
	@ResponseBody
	public JSONResult creditTransfer(Long[] bidId) {
		JSONResult result = new JSONResult();
		try {
			this.creditTransferService.creditTransfer(bidId);
		} catch (DisplayableException ex) {
			result = new JSONResult(false, ex.getMessage());
		} catch (Exception e) {
			// 把错误信息记录到服务器中日志文件中,方便排查问题.
			result = new JSONResult(false, "系统异常,请联系管理员!");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 我转让中的债权
	 */
	@RequestMapping("listMyTransferCredit")
	public String listMyTransferCredit(@ModelAttribute("qo") CreditTransferQueryObject qo, Model model) {
		qo.setState(Constants.BIDREQUEST_STATE_BIDDING);
		qo.setTransFromId(UserContext.getCurrent().getId());
		model.addAttribute("pageResult", this.creditTransferService.query(qo));
		return "credittrans/credittransfer_mytrans_list";
	}

	/**
	 * 认购一个债权转让标
	 */
	@RequestMapping("subscribe")
	@ResponseBody
	public JSONResult subscribe(Long id) {
		JSONResult result = new JSONResult();
		try {
			this.creditTransferService.subscribe(id);
		} catch (DisplayableException ex) {
			result = new JSONResult(false, ex.getMessage());
		} catch (Exception e) {
			// 把错误信息记录到服务器中日志文件中,方便排查问题.
			result = new JSONResult(false, "系统异常,请联系管理员!");
			e.printStackTrace();
		}
		return result;
	}

}
